package org.dong.Pojo;

import org.dong.Tool.Data;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class HttpRequest {
    private String RequestHead;//请求头
    private String RequestLine;//请求行
    private String RequestMethod;//请求方式
    private String url;//请求url
    private String RequestData;//请求体 请求参数

    public void setStatus(int status) {
        this.status = status;
    }

    private int status = 200;

    public HttpRequest(InputStream is) {
        byte[] buf = new byte[1024 * 1024];
//        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
        int let = 0;
        try {

            let = is.read(buf);

            if(let == -1){
               status = 404;
               let = 0;
            }
            String Msg = new String(buf, 0, let, StandardCharsets.UTF_8);
            this.RequestHead = Msg.split("\r\n")[0];
            this.RequestMethod = RequestHead.split(" ")[0];
            this.url = RequestHead.split(" ")[1];
            //如果是post方式的话解析参数在请求体 get方式解析参数在资源路径
            if(RequestMethod.equals("POST")){

                this.RequestData = Msg.split("\r\n")[Msg.split("\r\n").length-1];
            }else if(RequestMethod.equals("GET")){

                //解析get请求的参数
                if(RequestHead.contains("?")){
                    this.RequestData = (RequestHead.split(" ")[1]).split("?")[1];
                    this.url = RequestHead.split(" ")[1];
                }else{
                    this.RequestData = RequestHead.split(" ")[1];
                    this.url = RequestData;
                }


            }else{
                this.RequestData = RequestHead.split(" ")[1];
                //解析get请求的参数
                this.url = RequestData;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getRequestHead() {
        return RequestHead;
    }

    public void setRequestHead(String requestHead) {
        RequestHead = requestHead;
    }

    public String getRequestLine() {
        return RequestLine;
    }

    public void setRequestLine(String requestLine) {
        RequestLine = requestLine;
    }

    public String getRequestMethod() {
        return RequestMethod;
    }

    public void setRequestMethod(String requestMethod) {
        RequestMethod = requestMethod;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getRequestData() {
        return RequestData;
    }

    public void setRequestData(String requestData) {
        RequestData = requestData;
    }

    public int getStatus() {
        return status;
    }
}
